package com.uto;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import com.uto.backend.interfaces.IServerResponse;
import com.uto.frontend.interfaces.IServiceListener;

public class Register extends Activity implements OnClickListener {

	private ProgressDialog pd;

	private User user;
	
	private final int IS_OK = 0;
	private final int NOT_OK = 1;
	private final int INT_MONEY=500;
	private EditText firstnameField;
	private EditText lastnameField;
	private EditText usernameField;
	private EditText password1Field;
	private EditText password2Field;


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);

		// Set up click listener for register button
		View newPicButton = this.findViewById(R.id.RegisterButton);
		newPicButton.setOnClickListener(this);
		firstnameField = (EditText)this.findViewById(R.id.FirstNameEdit);
		lastnameField = (EditText)this.findViewById(R.id.LastNameEdit);
		usernameField = (EditText)this.findViewById(R.id.UsernameEdit);
		password1Field = (EditText)this.findViewById(R.id.PasswordEdit);
		password2Field = (EditText)this.findViewById(R.id.ReEnterPassEdit);


	}

	public void onClick(View v) {

		if (!allFieldsFilled()){
			Toast.makeText(Register.this, getString(R.string.fix_fields), Toast.LENGTH_SHORT).show();
			return;
		}

		if (!passwordMatch()){
			Toast.makeText(Register.this, getString(R.string.fix_passwords_match), Toast.LENGTH_SHORT).show();
			return;
		}
		String username = usernameField.getText().toString().trim();
		String password = password1Field.getText().toString().trim();
		String firstName = firstnameField.getText().toString().trim();
		String lastName = lastnameField.getText().toString().trim();
		user = new User(username , password , firstName , lastName);


		try {
			MyServiceConnection.getAppManager().register(user , listener);
			pd = ProgressDialog.show(this, getString(R.string.signing_in) , getString(R.string.may_take_time), true, false);
		} catch (Exception e) {
			if (pd!=null && pd.isShowing())
				pd.dismiss();
			Toast.makeText(Register.this, getString(R.string.signin_fail), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		//storeNewUser();
		//startActivity(new Intent(Register.this , GameChooser.class));
	}

	private boolean allFieldsFilled(){
		boolean ok = true;

		ok = checkField(usernameField) && ok; //"&& ok" has to be the second check, so the first always gets checked 
		ok = checkField(password1Field) && ok;//"&& ok" has to be the second check, so the first always gets checked
		ok = checkField(password2Field) && ok;//"&& ok" has to be the second check, so the first always gets checked
		ok = checkField(firstnameField) && ok;//"&& ok" has to be the second check, so the first always gets checked
		ok = checkField(lastnameField) && ok;//"&& ok" has to be the second check, so the first always gets checked
		return ok;
	}

	private boolean checkField(EditText field){
		if (field.getText()==null || field.getText().toString().trim().length()==0){
			field.setError(getString(R.string.can_not_be_empty));
			return false;
		}
		return true;
	}

	private boolean passwordMatch(){
		return password1Field.getText().toString().trim().equals(password2Field.getText().toString().trim());
	}


	private void storeNewUser() {
		SharedPreferences settings = getSharedPreferences(UTO.USER_FILE, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("firstName", user.getFirstName());
		editor.putString("lastName", user.getLastName());
		editor.putString("username", user.getUsername());
		editor.putString("password", user.getPassword());
		// Commit the edits!
		editor.commit();

	}

	private Handler handler = new Handler(){
		public void handleMessage(Message msg){

			if (pd!=null && pd.isShowing())
				pd.dismiss();

			if (msg.arg1==NOT_OK){
				String message = (String)msg.obj;
				if (message != null)
					Toast.makeText(Register.this, message, Toast.LENGTH_LONG).show();
				else
					Toast.makeText(Register.this, getString(R.string.signin_fail), Toast.LENGTH_LONG).show();
			}
			else{
				storeNewUser();
				Intent intent = new Intent(Register.this , GameChooser.class);
				intent.putExtra("user", user);
				startActivity(intent);
			}

		}

	};

private final IServiceListener.Stub listener = new IServiceListener.Stub(){

	public void handleMessage(IServerResponse response) {
		
		Message msg = new Message();
		try {
			if (response == null)
			{
				msg.arg1 = NOT_OK;
				handler.sendMessage(msg);
				Log.e("REGISTER", "null response");
			}

			else if (response.isOk())
			{
				msg.arg1 = IS_OK;
				handler.sendMessage(msg);
			}
			else{
				msg.arg1 = NOT_OK;
				msg.obj = response.getMessage();
				handler.sendMessage(msg);
			}
		} catch (RemoteException e) {
			msg.arg1 = NOT_OK;
			msg.obj = getString(R.string.signin_fail);
			handler.sendMessage(msg);
			e.printStackTrace();
		}
	}
};

}

